package com.redis.cluster;

import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

/**
 * 集群操作
 */
public class RedisCluster {
	public static void main(String[] args) {
		// 创建集群节点对象
		Set<HostAndPort> nodes = new HashSet<HostAndPort>();
		nodes.add(new HostAndPort("192.168.88.135", 6379));
		nodes.add(new HostAndPort("192.168.88.136", 6379));
		nodes.add(new HostAndPort("192.168.88.139", 6379));
		nodes.add(new HostAndPort("192.168.88.141", 6379));
		nodes.add(new HostAndPort("192.168.88.143", 6379));
		nodes.add(new HostAndPort("192.168.88.144", 6379));
		// 创建集群操作对象
		JedisCluster cluster = new JedisCluster(nodes);

		// 获取集群的所有key
		Set<String> keys = new TreeSet<>();
		Map<String, JedisPool> clusterNodes = cluster.getClusterNodes();
		for(String node : clusterNodes.keySet()){
			Jedis jedis = clusterNodes.get(node).getResource();
			keys.addAll(jedis.keys("*"));
		}
		
		// 遍历所有key
		for (String key : keys) {
			System.out.println(key + " = " + cluster.get(key));
		}
		
		try {
			// 关闭集群操作
			cluster.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
